package transaction;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.concurrent.TimeUnit;

/**
 * Created by yangwang on 2015/1/23.
 */
public class TransactionExecutor {

    public static void main(String[] args) throws SQLException {
        TransactionExecutor executor = new TransactionExecutor();
        executor.execute();
    }

    public void execute() throws SQLException {
        Connection connection = DriverManager.getConnection("jdbc:mysql://master.mysql.mhs.com/mhs_daily?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true",
                "mhs", "mhstcl");
        connection.setAutoCommit(false);
        PreparedStatement preparedStatement =
                connection.prepareStatement("INSERT INTO `person_test` (`name`,`age`,`birthday`) VALUES (?,?,now());");
        String[][] data = new String[][]{
                {"nova", "21"},
                {"ellen", "24"},
        };

        for (String[] entity : data){
            preparedStatement.setString(1, entity[0]);
            preparedStatement.setString(2, entity[1]);
            preparedStatement.addBatch();

        }
        preparedStatement.executeUpdate();
        System.out.print("statement executed.");
        sleep(5, TimeUnit.SECONDS);
        connection.rollback();
    }

    protected void sleep(int time, TimeUnit timeUnit){
        long millisecond = timeUnit.toMillis(time);
        try {
            Thread.sleep(millisecond);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
